"use strict";

const Controller = require("egg").Controller;

class ProductController extends Controller {
  /**
   * 获取商品列表
   */
  async index() {
    const { ctx } = this;
    const {
      name,
      description,
      categoryId,
      brandId,
      keyword,
      isHot,
      isNew,
      isRecommend,
      status,
      page = 1,
      pageSize = 20,
    } = ctx.query;

    const productData = {
      name,
      description,
      categoryId,
      brandId,
      keyword,
      isHot,
      isNew,
      isRecommend,
      status,
    };

    const products = await ctx.service.product.getList(
      productData,
      parseInt(page),
      parseInt(pageSize)
    );

    ctx.body = {
      code: 0,
      message: "success",
      data: products,
    };
  }

  /**
   * 获取商品详情
   */
  async getDetail() {
    const { ctx } = this;
    const { id } = ctx.params;

    const product = await ctx.service.product.getById(id);

    ctx.body = {
      code: 0,
      message: "success",
      data: product,
    };
  }

  /**
   * 创建商品
   */
  async create() {
    const { ctx } = this;
    const productData = ctx.request.body;

    const product = await ctx.service.product.create(productData);

    ctx.body = {
      code: 0,
      message: "创建成功",
      data: product,
    };
  }

  /**
   * 更新商品
   */
  async update() {
    const { ctx } = this;
    const { id } = ctx.params;
    const productData = ctx.request.body;

    const result = await ctx.service.product.update(id, productData);

    ctx.body = {
      code: 0,
      message: "更新成功",
      data: result,
    };
  }

  /**
   * 删除商品
   */
  async destroy() {
    const { ctx } = this;
    const { id } = ctx.params;

    const result = await ctx.service.product.delete(id);

    ctx.body = {
      code: 0,
      message: "删除成功",
      data: result,
    };
  }

  /**
   * 更新商品库存
   */
  async updateStock() {
    const { ctx } = this;
    const { id } = ctx.params;
    const { changeType, changeNum, specId } = ctx.request.body;

    const result = await ctx.service.product.updateStock(
      id,
      changeType,
      parseInt(changeNum),
      specId
    );

    ctx.body = {
      code: 0,
      message: "更新成功",
      data: result,
    };
  }
}

module.exports = ProductController;
